﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.Reflection;

using Sabnzbd;
using Bierdopje.API;
using AutoDownload.Lib;
using AutoDownload.Settings;

namespace AutoDownload.Service
{
    public partial class Service : ServiceBase
    {
        public Service()
        {
            InitializeComponent();
        }

        Thread _T;

        protected override void OnStart(string[] args)
        {
            _T = new Thread(new ThreadStart(Run));
            _T.Start();
        }

        protected override void OnStop()
        {
            try
            {
                _T.Abort();
            }
            catch (ThreadAbortException) { }
        }

        protected override void OnPause()
        {
            _T.Suspend();
            base.OnPause();
        }

        protected override void OnShutdown()
        {
            try
            {
                _T.Abort();
            }
            catch (ThreadAbortException) { }
            base.OnShutdown();
        }

        protected override void OnContinue()
        {
            _T.Resume();
            base.OnContinue();
        }

        private void Run()
        {
            try
            {
                Bierdopje.API.HTTPHelper.UserAgent = "AutoDownloadSub/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                string sSource;
                string sLog;
                string sEvent;

                sSource = "AutoSubDownload";
                sLog = "Application";

                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);

                Sabnzbd.szdConfig _Config = SABnzbd.ParseINIFile(Config.Load(Config.GetConfigFileName()).SabnzbdINI);

                while (true)
                {
                    try
                    {
                        try
                        {
                            Downloader _Downloader = new Downloader(Config.GetConfigFileName());
                            _Downloader.Check();

                        }
                        catch (ThreadAbortException) { break; }
                        catch (WebException E)
                        {
                            sEvent = "Can not establish a connection to host: " + E.Message;
                            EventLog.WriteEntry(sSource, sEvent,
                                EventLogEntryType.Warning, 2);
                        }
                        catch (SmtpException E)
                        {
                            sEvent = "Can not send email a to host (" + _Config.Email.Server + "): " + E.Message;
                            EventLog.WriteEntry(sSource, sEvent,
                                EventLogEntryType.Warning, 3);
                        }
                        catch (Exception E)
                        {

                            sEvent = "Error has occured in the Subtitle Download service: " + E.Message;
                            EventLog.WriteEntry(sSource, sEvent,
                                EventLogEntryType.Error, 1);

                            try
                            {
                                if (_Config.Email.Server != "")
                                {
                                    SmtpClient _SC = _Config.Email.getSmtpClient();
                                    MailMessage _MM = new MailMessage(new MailAddress(_Config.Email.From), new MailAddress(_Config.Email.To));

                                    _MM.Subject = "Error occured in Subtitle Service";
                                    _MM.Body = "Hi,\r\n" +
                                        "\r\n" +
                                        "A error occured: " + E.Message + "\r\n" +
                                        "\r\n" +
                                        "Stacktrace: " + E.StackTrace + "\r\n" +
                                        "\r\n" +
                                        "Enjoy! ;-)\r\n";

                                    _SC.Send(_MM);
                                }
                            }
                            catch (ThreadAbortException) { }
                            catch (Exception E2)
                            {
                                sEvent = "Error has occured in the Subtitle Download can not send error log: " + E2.Message;
                                EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error, 4);
                            }

                            this.Stop();
                            break;
                        }

                        // Go in holding pattern....
                        DateTime _timeToRunAgain = DateTime.Now.Add(new TimeSpan(0, 15, 0));
                        while (_timeToRunAgain > DateTime.Now)
                        {
                            Thread.Sleep(0);
                            Thread.Sleep(1000);
                        }
                    }
                    catch (ThreadAbortException) { break; }
                    catch (Exception E)
                    {
                        sEvent = "General Error has occured in the Subtitle Download service: " + E.Message;
                        EventLog.WriteEntry(sSource, sEvent,
                            EventLogEntryType.Error, 5);

                        this.Stop();
                        break;
                    }
                }
            }
            catch (ThreadAbortException) { }
        }
    }
}
